package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.TokenException;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author YangJiaHao
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    // @Autowired
    // private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            throw new TokenException();
        }
        // Employee employee = employeeMapper.getByToken(token);
        String emp = redisTemplate.opsForValue().get("employee_token:" + token);

        //将json字符串转为对象
        Employee employee = JSON.parseObject(emp, Employee.class);
        if (employee == null) {
            throw new TokenException();
        }
        redisTemplate.opsForValue().set("employee_token:"+token,JSON.toJSONString(employee),30, TimeUnit.MINUTES);
        return true;
    }
}
